using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Core.Models;
using WalkingTec.Mvvm.Core.Support.FileHandlers;
using WalkingTec.Mvvm.Core.Support.Json;
using WalkingTec.Mvvm.Mvc;

namespace ReceiptPrint.Controllers;

[AllRights]
[ActionDescription("Framework")]
public class _FrameworkController : BaseController
{

    [HttpPost]
    [Public]
    public IActionResult Selector(string _DONOT_USE_VMNAME, string _DONOT_USE_KFIELD, string _DONOT_USE_VFIELD, string _DONOT_USE_FIELD, bool _DONOT_USE_MULTI_SEL, string _DONOT_USE_SEL_ID, string _DONOT_USE_SUBMIT, string _DONOT_USE_LINK_FIELD, string _DONOT_USE_TRIGGER_URL, string _DONOT_USE_CURRENTCS)
    {
        base.Wtm.CurrentCS = _DONOT_USE_CURRENTCS;
        IBasePagedListVM<TopBasePoco, ISearcher> listVM = base.Wtm.CreateVM(_DONOT_USE_VMNAME, null, null, passInit: true) as IBasePagedListVM<TopBasePoco, ISearcher>;
        if (listVM != null)
        {
            RedoUpdateModel(listVM);
        }

        listVM.SearcherMode = ListVMSearchModeEnum.Selector;
        listVM.RemoveActionColumn();
        listVM.RemoveAction();
        base.ViewBag.TextName = _DONOT_USE_KFIELD;
        base.ViewBag.ValName = _DONOT_USE_VFIELD;
        base.ViewBag.FieldName = _DONOT_USE_FIELD;
        base.ViewBag.MultiSel = _DONOT_USE_MULTI_SEL;
        base.ViewBag.SelId = _DONOT_USE_SEL_ID;
        base.ViewBag.SubmitFunc = _DONOT_USE_SUBMIT;
        base.ViewBag.LinkField = _DONOT_USE_LINK_FIELD;
        base.ViewBag.TriggerUrl = _DONOT_USE_TRIGGER_URL;
        base.ViewBag.CurrentCS = _DONOT_USE_CURRENTCS;
        base.ViewBag.SelectData = "[]";
        base.ViewBag.SelectorValueField = _DONOT_USE_VFIELD;
        List<string> ids = listVM.Ids;
        if (ids != null && ids.Count > 0)
        {
            List<FrameworkRole> list = (from x in base.DC.Set<FrameworkRole>()
                                        where listVM.Ids.Contains(x.RoleName)
                                        select x).ToList();
            listVM.DC = base.Wtm.CreateDC();
            bool needPage = listVM.NeedPage;
            listVM.NeedPage = false;
            listVM.SearcherMode = ListVMSearchModeEnum.Batch;
            Type modelType = listVM.ModelType;
            ParameterExpression expression = Expression.Parameter(modelType);
            PropertyInfo singleProperty = modelType.GetSingleProperty(_DONOT_USE_VFIELD);
            MemberExpression peid = Expression.Property(expression, singleProperty);
            listVM.ReplaceWhere = listVM.Ids.GetContainIdExpression(modelType, Expression.Parameter(modelType), peid);
            Regex regex = new Regex("<script>.*?</script>");
            string text = regex.Replace((listVM as IBasePagedListVM<TopBasePoco, BaseSearcher>).GetDataJson(), "");
            base.ViewBag.SelectData = text;
            listVM.IsSearched = false;
            listVM.SearcherMode = ListVMSearchModeEnum.Selector;
            listVM.NeedPage = needPage;
        }

        return PartialView(listVM);
    }

    [ActionDescription("GetEmptyData")]
    public IActionResult GetEmptyData(string _DONOT_USE_VMNAME)
    {
        IBasePagedListVM<TopBasePoco, BaseSearcher> self = base.Wtm.CreateVM(_DONOT_USE_VMNAME, null, null, passInit: true) as IBasePagedListVM<TopBasePoco, BaseSearcher>;
        string singleDataJson = self.GetSingleDataJson(null, returnColumnObject: false);
        return new ContentResult
        {
            ContentType = "application/json",
            Content = singleDataJson
        };
    }

    //
    // 摘要:
    //     获取分页数据
    //
    // 参数:
    //   _DONOT_USE_VMNAME:
    //
    //   _DONOT_USE_CS:
    [HttpPost]
    [ActionDescription("GetPagingData")]
    public IActionResult GetPagingData(string _DONOT_USE_VMNAME, string _DONOT_USE_CS)
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        foreach (string key in base.Request.Form.Keys)
        {
            dictionary.Add(key, base.Request.Form[key]);
        }

        base.Wtm.CurrentCS = _DONOT_USE_CS;
        IBasePagedListVM<TopBasePoco, BaseSearcher> basePagedListVM = base.Wtm.CreateVM(_DONOT_USE_VMNAME, null, null, passInit: true) as IBasePagedListVM<TopBasePoco, BaseSearcher>;
        basePagedListVM.FC = dictionary;
        if (basePagedListVM != null)
        {
            RedoUpdateModel(basePagedListVM);
            string text = "";
            if (base.ConfigInfo.HasMainHost && base.Wtm.LoginUserInfo?.CurrentTenant == null)
            {
                Type[] array = new Type[3]
                {
                    typeof(FrameworkUserBase),
                    typeof(FrameworkGroup),
                    typeof(FrameworkRole)
                };
                if (typeof(FrameworkUserBase).IsAssignableFrom(basePagedListVM.ModelType))
                {
                    text = "/api/_frameworkuser/search";
                }
                else if (typeof(FrameworkGroup).IsAssignableFrom(basePagedListVM.ModelType))
                {
                    text = "/api/_frameworkgroup/search";
                }
                else if (typeof(FrameworkRole).IsAssignableFrom(basePagedListVM.ModelType))
                {
                    text = "/api/_frameworkrole/search";
                }
            }

            if (!string.IsNullOrEmpty(text))
            {
                ApiResult<string> result = base.Wtm.CallAPI<string>("mainhost", text, HttpMethodEnum.POST, basePagedListVM.Searcher, 10).Result;
                return new ContentResult
                {
                    ContentType = "application/json",
                    Content = result.Data
                };
            }

            return new ContentResult
            {
                ContentType = "application/json",
                Content = $"{{\"Data\":{basePagedListVM.GetDataJson()},\"Count\":{basePagedListVM.Searcher.Count},\"Msg\":\"success\",\"Code\":{200}}}"
            };
        }

        throw new Exception("Invalid Vm Name");
    }

    //
    // 摘要:
    //     单元格编辑
    //
    // 参数:
    //   _DONOT_USE_VMNAME:
    //
    //   id:
    //     实体主键
    //
    //   field:
    //     属性名
    //
    //   value:
    //     属性值
    [HttpPost]
    public IActionResult UpdateModelProperty(string _DONOT_USE_VMNAME, Guid id, string field, string value)
    {
        if (value == null && StringValues.IsNullOrEmpty(base.Request.Form["value"]))
        {
            value = string.Empty;
        }

        IBaseCRUDVM<TopBasePoco> baseCRUDVM = base.Wtm.CreateVM(_DONOT_USE_VMNAME, id, null, passInit: true) as IBaseCRUDVM<TopBasePoco>;
        baseCRUDVM.Entity.SetPropertyValue(field, value);
        base.DC.SaveChanges();
        return JsonMore("Success");
    }

    //
    // 摘要:
    //     Download Excel
    //
    // 参数:
    //   _DONOT_USE_VMNAME:
    //
    //   _DONOT_USE_CS:
    [HttpPost]
    [ActionDescription("Export")]
    public IActionResult GetExportExcel(string _DONOT_USE_VMNAME, string _DONOT_USE_CS)
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        foreach (string key in base.Request.Query.Keys)
        {
            dictionary.Add(key, base.Request.Query[key]);
        }

        foreach (KeyValuePair<string, StringValues> item in base.Request.Form)
        {
            if (!dictionary.ContainsKey(item.Key))
            {
                dictionary.Add(item.Key, item.Value);
            }
        }

        Type type = Type.GetType(_DONOT_USE_VMNAME);
        base.Wtm.CurrentCS = _DONOT_USE_CS;
        IBasePagedListVM<TopBasePoco, ISearcher> basePagedListVM = base.Wtm.CreateVM(_DONOT_USE_VMNAME) as IBasePagedListVM<TopBasePoco, ISearcher>;
        basePagedListVM.FC = dictionary;
        if (basePagedListVM != null)
        {
            RedoUpdateModel(basePagedListVM);
            basePagedListVM.SearcherMode = ((basePagedListVM.Ids == null || basePagedListVM.Ids.Count <= 0) ? ListVMSearchModeEnum.Export : ListVMSearchModeEnum.CheckExport);
            byte[] fileContents = basePagedListVM.GenerateExcel();
            base.HttpContext.Response.Cookies.Append("DONOTUSEDOWNLOADING", "0", new CookieOptions
            {
                Path = "/",
                Expires = DateTime.Now.AddDays(2.0)
            });
            return File(fileContents, "application/vnd.ms-excel", $"Export_{type.Name}_{DateTime.Now.ToString("yyyy-MM-dd")}.xls");
        }

        throw new Exception("Invalid Vm Name");
    }

    //
    // 摘要:
    //     Download Excel Template
    [HttpGet]
    [ActionDescription("DownloadTemplate")]
    public IActionResult GetExcelTemplate(string _DONOT_USE_VMNAME, string _DONOT_USE_CS)
    {
        IBaseImport<BaseTemplateVM> baseImport = base.Wtm.CreateVM(_DONOT_USE_VMNAME) as IBaseImport<BaseTemplateVM>;
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        foreach (string key in base.Request.Query.Keys)
        {
            dictionary.Add(key, base.Request.Query[key]);
        }

        baseImport.SetParms(dictionary);
        string displayName;
        byte[] fileContents = baseImport.GenerateTemplate(out displayName);
        base.HttpContext.Response.Cookies.Append("DONOTUSEDOWNLOADING", "0", new CookieOptions
        {
            Domain = "/",
            Expires = DateTime.Now.AddDays(2.0)
        });
        return File(fileContents, "application/vnd.ms-excel", displayName);
    }

    [AllowAnonymous]
    [ActionDescription("Sys.ErrorHandle")]
    public IActionResult Error()
    {
        IExceptionHandlerPathFeature exceptionHandlerPathFeature = base.HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        ActionLog actionLog = new ActionLog();
        actionLog.LogType = ActionLogTypesEnum.Exception;
        actionLog.ActionTime = DateTime.Now;
        actionLog.ITCode = base.Wtm.LoginUserInfo?.ITCode ?? string.Empty;
        ActionDescriptionAttribute actionDescriptionAttribute = exceptionHandlerPathFeature.Error.TargetSite.DeclaringType.GetCustomAttributes(typeof(ActionDescriptionAttribute), inherit: false).Cast<ActionDescriptionAttribute>().FirstOrDefault();
        ActionDescriptionAttribute actionDescriptionAttribute2 = exceptionHandlerPathFeature.Error.TargetSite.GetCustomAttributes(typeof(ActionDescriptionAttribute), inherit: false).Cast<ActionDescriptionAttribute>().FirstOrDefault();
        HttpPostAttribute httpPostAttribute = exceptionHandlerPathFeature.Error.TargetSite.GetCustomAttributes(typeof(HttpPostAttribute), inherit: false).Cast<HttpPostAttribute>().FirstOrDefault();
        actionLog.ModuleName = actionDescriptionAttribute?.GetDescription(exceptionHandlerPathFeature.Error.TargetSite.DeclaringType) ?? exceptionHandlerPathFeature.Error.TargetSite.DeclaringType.Name.Replace("Controller", string.Empty);
        actionLog.ActionName = actionDescriptionAttribute2?.GetDescription(exceptionHandlerPathFeature.Error.TargetSite.DeclaringType) ?? exceptionHandlerPathFeature.Error.TargetSite.Name;
        if (httpPostAttribute != null)
        {
            actionLog.ActionName += "[P]";
        }

        actionLog.ActionUrl = exceptionHandlerPathFeature.Path;
        actionLog.IP = base.HttpContext.Connection.RemoteIpAddress.ToString();
        actionLog.Remark = exceptionHandlerPathFeature.Error.ToString();
        if (!string.IsNullOrEmpty(actionLog.Remark) && actionLog.Remark.Length > 2000)
        {
            actionLog.Remark = actionLog.Remark.Substring(0, 2000);
        }

        DateTime? dateTime = base.HttpContext.Items["actionstarttime"] as DateTime?;
        if (dateTime.HasValue)
        {
            actionLog.Duration = DateTime.Now.Subtract(dateTime.Value).TotalSeconds;
        }

        base.HttpContext.RequestServices.GetRequiredService<ILogger<ActionLog>>()?.Log(LogLevel.Error, default(EventId), actionLog, null, (ActionLog a, Exception? b) => a.GetLogString());
        string empty = string.Empty;
        empty = ((!base.ConfigInfo.IsQuickDebug) ? exceptionHandlerPathFeature.Error.Message.Replace(Environment.NewLine, "<br />") : exceptionHandlerPathFeature.Error.ToString().Replace(Environment.NewLine, "<br />"));
        return BadRequest(empty);
    }

    [HttpPost]
    [ActionDescription("UploadFileRoute")]
    public IActionResult Upload([FromServices] WtmFileProvider fp, string sm = null, string groupName = null, string subdir = null, string extra = null, bool IsTemprory = true, string _DONOT_USE_CS = null)
    {
        IFormFile formFile = base.Request.Form.Files[0];
        IWtmFile wtmFile = fp.Upload(formFile.FileName, formFile.Length, formFile.OpenReadStream(), groupName, subdir, extra, sm, base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS));
        return JsonMore(new
        {
            Id = wtmFile.GetID(),
            Name = wtmFile.FileName
        });
    }

    [HttpPost]
    [ActionDescription("UploadFileRoute")]
    public IActionResult UploadImage([FromServices] WtmFileProvider fp, string sm = null, string groupName = null, string subdir = null, string extra = null, bool IsTemprory = true, string _DONOT_USE_CS = null, int? width = null, int? height = null)
    {
        if (!width.HasValue && !height.HasValue)
        {
            return Upload(fp, sm, groupName, subdir, extra, IsTemprory, _DONOT_USE_CS);
        }

        IFormFile formFile = base.Request.Form.Files[0];
        Image image = Image.Load(formFile.OpenReadStream());
        if (image == null)
        {
            return JsonMore(new
            {
                Id = string.Empty,
                Name = string.Empty
            }, 404);
        }

        if (!width.HasValue)
        {
            width = height * image.Width / image.Height;
        }

        if (!height.HasValue)
        {
            height = width * image.Height / image.Width;
        }

        MemoryStream memoryStream = new MemoryStream();
        image.Mutate(delegate (IImageProcessingContext x)
        {
            x.Resize(width.Value, height.Value);
        });
        image.SaveAsJpeg(memoryStream);
        memoryStream.Position = 0L;
        IWtmFile wtmFile = fp.Upload(formFile.FileName, memoryStream.Length, memoryStream, groupName, subdir, extra, sm, base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS));
        image.Dispose();
        memoryStream.Dispose();
        return JsonMore(new
        {
            Id = wtmFile.GetID(),
            Name = wtmFile.FileName
        });
    }

    [HttpPost]
    [ActionDescription("UploadForLayUIRichTextBox")]
    public IActionResult UploadForLayUIRichTextBox([FromServices] WtmFileProvider fp, string _DONOT_USE_CS = null, string groupName = null, string subdir = null)
    {
        IFormFile formFile = base.Request.Form.Files[0];
        IWtmFile wtmFile = fp.Upload(formFile.FileName, formFile.Length, formFile.OpenReadStream(), groupName, subdir, null, null, base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS));
        if (wtmFile != null)
        {
            string text = "/_Framework/GetFile?id=" + wtmFile.GetID() + "&stream=true&_DONOT_USE_CS=" + base.CurrentCS;
            return Content("{\"code\": 0 , \"msg\": \"\", \"data\": {\"src\": \"" + text + "\"}}");
        }

        return Content($"{{\"code\": 1 , \"msg\": \"{MvcProgram._localizer["Sys.UploadFailed"]}\", \"data\": {{\"src\": \"\"}}}}");
    }

    [ActionDescription("GetFileName")]
    public IActionResult GetFileName([FromServices] WtmFileProvider fp, Guid id, string _DONOT_USE_CS)
    {
        return Ok(fp.GetFileName(id.ToString(), base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS)));
    }

    [ActionDescription("GetFile")]
    public async Task<IActionResult> GetFile([FromServices] WtmFileProvider fp, string id, bool stream = false, string _DONOT_USE_CS = null, int? width = null, int? height = null)
    {
        IWtmFile file = fp.GetFile(id, withData: true, base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS));
        if (file == null)
        {
            return new EmptyResult();
        }

        Stream rv = null;
        try
        {
            rv = file.DataStream;
            Image image = Image.Load(rv);
            if (image != null && (width.HasValue || height.HasValue))
            {
                if (!width.HasValue)
                {
                    width = image.Width * height / image.Height;
                }

                if (!height.HasValue)
                {
                    height = image.Height * width / image.Width;
                }

                MemoryStream memoryStream = new MemoryStream();
                image.Mutate(delegate (IImageProcessingContext x)
                {
                    x.Resize(width.Value, height.Value);
                });
                image.SaveAsJpeg(memoryStream);
                rv.Dispose();
                rv = memoryStream;
            }
        }
        catch
        {
        }

        string text = file.FileExt.ToLower();
        string contentType = "application/octet-stream";
        if (text == "pdf")
        {
            contentType = "application/pdf";
        }

        switch (text)
        {
            case "png":
            case "bmp":
            case "gif":
            case "tif":
            case "jpg":
            case "jpeg":
                contentType = "image/" + text;
                break;
        }

        if (text == "mp4")
        {
            contentType = "video/mpeg4";
        }

        rv.Position = 0L;
        if (!stream)
        {
            return File(rv, contentType, file.FileName ?? (Guid.NewGuid().ToString() + text));
        }

        if (text == "mp4")
        {
            return File(rv, contentType, enableRangeProcessing: true);
        }

        base.Response.Headers.TryAdd("Content-Disposition", "inline; filename=\"" + HttpUtility.UrlEncode(file.FileName) + "\"");
        await rv.CopyToAsync(base.Response.Body);
        rv.Dispose();
        return new EmptyResult();
    }

    [ActionDescription("ViewFile")]
    public IActionResult ViewFile([FromServices] WtmFileProvider fp, string id, string width, string _DONOT_USE_CS = null)
    {
        IWtmFile file = fp.GetFile(id, withData: false, base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS));
        string empty = string.Empty;
        string text = file.FileExt.ToLower();
        empty = ((text == "pdf") ? ("\r\n<embed src=\"/_Framework/GetFile?id=" + id + "&stream=true\" width=\"100%\" height=\"100%\" type=\"application/pdf\" ></embed>\r\n            ") : ((!(text == "mp4")) ? $"<img id='FileObject' style='flex:auto;{(string.IsNullOrEmpty(width) ? "" : ("width:" + width + "px"))}'  border=0 src='/_Framework/GetFile?id={id}&stream=true&_DONOT_USE_CS={_DONOT_USE_CS}'/>" : $"<video id='FileObject' controls='controls' style='{(string.IsNullOrEmpty(width) ? "" : ("width:" + width + "px"))}'  border=0 src='/_Framework/GetFile?id={id}&stream=true&_DONOT_USE_CS={_DONOT_USE_CS}'></video>"));
        return Content(empty);
    }

    [Public]
    public IActionResult OutSide(string url)
    {
        url = HttpUtility.UrlDecode(url);
        string text = string.Empty;
        SimpleMenu menu = Utils.FindMenu(url, base.Wtm.GlobaInfo.AllMenus);
        if (menu != null)
        {
            if (menu.ParentId.HasValue)
            {
                SimpleMenu simpleMenu = base.GlobaInfo.AllMenus.Where(delegate (SimpleMenu x)
                {
                    Guid iD = x.ID;
                    Guid? parentId = menu.ParentId;
                    return iD == parentId;
                }).FirstOrDefault();
                if (simpleMenu != null)
                {
                    simpleMenu.PageName = CoreProgram._localizer?[simpleMenu.PageName];
                    text = simpleMenu.PageName + " - ";
                }
            }

            menu.PageName = CoreProgram._localizer?[menu.PageName];
            text += menu.PageName;
        }

        if (base.Wtm.IsUrlPublic(url) || base.Wtm.IsAccessable(url))
        {
            return Content($"<title>{text}</title>\r\n<iframe src='{url}' frameborder='0' class='layadmin-iframe'></iframe>");
        }

        throw new Exception(MvcProgram._localizer["Sys.NoPrivilege"]);
    }

    [HttpGet]
    public IActionResult Menu()
    {
        List<LayUIMenu> data = base.GlobaInfo.AllMenus.ToLayuiMenu(base.Wtm);
        return Content(JsonSerializer.Serialize(new
        {
            Code = 200,
            Msg = string.Empty,
            Data = data
        }, new JsonSerializerOptions
        {
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
        }), "application/json");
    }

    [AllowAnonymous]
    public IActionResult IsAccessable(string url)
    {
        url = HttpUtility.UrlDecode(url);
        if (base.Wtm.LoginUserInfo == null)
        {
            if (base.Wtm.IsUrlPublic(url))
            {
                return Ok(true);
            }

            return Unauthorized();
        }

        bool flag = base.Wtm.IsAccessable(url);
        return Ok(flag);
    }



    [AllowAnonymous]
    [ResponseCache(Duration = 3600)]
    public string Redirect()
    {
        return "";
    }

    [AllowAnonymous]
    public ActionResult GetVerifyCode()
    {
        int num = 80;
        int num2 = 30;
        int num3 = 16;
        string chkCode = string.Empty;
        Color[] array = new Color[8]
        {
            Color.Black,
            Color.Red,
            Color.Blue,
            Color.Green,
            Color.Orange,
            Color.Brown,
            Color.DarkBlue,
            Color.PaleGreen
        };
        string[] array2 = new string[1] { "Times New Roman" };
        char[] array3 = new char[41]
        {
            '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
            'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x',
            'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
            'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X',
            'Y'
        };
        Random random = new Random();
        for (int j = 0; j < 4; j++)
        {
            chkCode += array3[random.Next(array3.Length)];
        }

        base.HttpContext.Session.Set("verify_code", chkCode);
        Image image = new Image<Rgba32>(num, num2);
        for (int k = 0; k < 3; k++)
        {
            float x2 = random.Next(num);
            float y1 = random.Next(num2);
            float x3 = random.Next(num);
            float y2 = random.Next(num2);
            Color clr2 = array[random.Next(array.Length)];
            image.Mutate(delegate (IImageProcessingContext x)
            {
                x.DrawLines(clr2, 1f, new PointF(x2, y1), new PointF(x3, y2));
            });
        }

        for (int i = 0; i < chkCode.Length; i++)
        {
            Font ft = new Font(SystemFonts.Get("Arial"), num3);
            Color clr = array[random.Next(array.Length)];
            image.Mutate(delegate (IImageProcessingContext x)
            {
                x.DrawText(chkCode[i].ToString(), ft, clr, new PointF((float)i * 18f, 0f));
            });
        }

        MemoryStream memoryStream = new MemoryStream();
        try
        {
            image.SaveAsPng(memoryStream);
            return File(memoryStream.ToArray(), "image/jpeg");
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            image.Dispose();
        }
    }

    [Public]
    public Dictionary<string, string> GetScriptLanguage()
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        dictionary.Add("DONOTUSE_Text_LoadFailed", MvcProgram._localizer["Sys.LoadFailed"]);
        dictionary.Add("DONOTUSE_Text_SubmitFailed", MvcProgram._localizer["Sys.SubmitFailed"]);
        dictionary.Add("DONOTUSE_Text_PleaseSelect", MvcProgram._localizer["Sys.PleaseSelect"]);
        dictionary.Add("DONOTUSE_Text_FailedLoadData", MvcProgram._localizer["Sys.FailedLoadData"]);
        return dictionary;
    }

    [AllRights]
    [HttpPost]
    [ActionDescription("UploadForLayUIUEditor")]
    public IActionResult UploadForLayUIUEditor([FromServices] WtmFileProvider fp, string _DONOT_USE_CS = "default", string groupName = null, string subdir = null)
    {
        IWtmFile wtmFile = null;
        if (base.Request.Form.Files != null && base.Request.Form.Files.Count() > 0)
        {
            IFormFile formFile = base.Request.Form.Files[0];
            wtmFile = fp.Upload(formFile.FileName, formFile.Length, formFile.OpenReadStream(), groupName, subdir, null, null, base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS));
        }
        else if (base.Request.Form.Keys != null && base.Request.Form.ContainsKey("FileID"))
        {
            byte[] array = Convert.FromBase64String(base.Request.Form["FileID"]);
            MemoryStream memoryStream = new MemoryStream(array);
            wtmFile = fp.Upload("SCRAWL_" + DateTime.Now.ToString("yyyyMMddHHmmssttt") + ".jpg", array.Length, memoryStream, groupName, subdir, null, null, base.Wtm.CreateDC(isLog: false, _DONOT_USE_CS));
            memoryStream.Dispose();
        }

        if (wtmFile != null)
        {
            string value = "/_Framework/GetFile?id=" + wtmFile.GetID() + "&stream=true&_DONOT_USE_CS=" + base.CurrentCS;
            return Content($"{{\"Code\": 200 , \"Msg\": \"success\", \"Data\": {{\"src\": \"{value}\",\"FileName\":\"{wtmFile.FileName}\"}}}}");
        }

        return Content($"{{\"code\": 1 , \"msg\": \"{MvcProgram._localizer["Sys.UploadFailed"]}\", \"data\": {{\"src\": \"\"}}}}");
    }

    [Public]
    [ActionDescription("加载UEditor配置文件")]
    [ResponseCache(Duration = 3600)]
    [HttpGet]
    public IActionResult UEditorOptions()
    {
        if (base.ConfigInfo.UEditorOptions == null)
        {
            throw new Exception("Unregistered service: UEditorOptions");
        }

        return JsonMore(base.ConfigInfo.UEditorOptions);
    }

    [Public]
    public IActionResult SetLanguage(string culture)
    {
        base.Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), new CookieOptions
        {
            Expires = DateTimeOffset.UtcNow.AddYears(1)
        });
        return FFResult().AddCustomScript("location.reload();");
    }

    [Public]
    public IActionResult SetTenant(string tenant)
    {
        base.Wtm.SetCurrentTenant((tenant == "") ? null : tenant);
        ClaimsPrincipal principal = base.Wtm.LoginUserInfo.CreatePrincipal();
        base.HttpContext.SignInAsync("Cookies", principal, null);
        return FFResult().AddCustomScript("location.reload();");
    }

    [Public]
    public IActionResult SetLanguageForBlazor(string culture, string redirect)
    {
        base.Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), new CookieOptions
        {
            Expires = DateTimeOffset.UtcNow.AddYears(1)
        });
        return Content("<script>window.location.href='" + HttpUtility.UrlDecode(redirect) + "';</script>", "text/html");
    }

    [Public]
    [HttpGet]
    public IActionResult Redirect401()
    {
        return Unauthorized();
    }

    [Public]
    public async Task<ActionResult> RemoteEntry(string redirect)
    {
        if (string.IsNullOrEmpty(redirect))
        {
            redirect = "/";
        }

        if (base.Wtm?.LoginUserInfo != null)
        {
            ClaimsPrincipal principal = base.Wtm.LoginUserInfo.CreatePrincipal();
            await base.HttpContext.SignInAsync("Cookies", principal, null);
        }

        return Content("<script>window.location.href='" + HttpUtility.UrlDecode(redirect) + "'</script>", "text/html");
    }

    [AllRights]
    [HttpPost]
    public async Task<ActionResult> RemoveUserCacheByAccount(string[] itcode)
    {
        await base.Wtm.RemoveUserCache(itcode);
        return Ok();
    }

    [AllRights]
    [HttpPost]
    public async Task<ActionResult> RemoveUserCacheByRole(string[] rolecode)
    {
        await base.Wtm.RemoveUserCacheByRole(rolecode);
        return Ok();
    }

    [AllRights]
    [HttpPost]
    public async Task<ActionResult> RemoveUserCacheByGroup(string[] groupcode)
    {
        await base.Wtm.RemoveUserCacheByGroup(groupcode);
        return Ok();
    }
}